#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的重复日志调试脚本
"""

# 首先修复可能的导入问题
import sys
import os
sys.path.insert(0, os.getcwd())

def patch_logging_middleware():
    """给日志中间件添加调用计数"""
    try:
        from tools.middlewares.logging_middleware import structured_logging_middleware
        
        # 添加调用计数器
        if not hasattr(structured_logging_middleware, 'call_count'):
            structured_logging_middleware.call_count = 0
        
        # 保存原始函数
        original_func = structured_logging_middleware.__wrapped__ if hasattr(structured_logging_middleware, '__wrapped__') else structured_logging_middleware
        
        def counting_middleware(request, call_next):
            structured_logging_middleware.call_count += 1
            print(f"🔍 [第{structured_logging_middleware.call_count}次] 中间件被调用")
            print(f"   API: {request.get('_api_meta', {}).get('class_name', 'Unknown')}")
            print(f"   URL: {request.get('url', 'N/A')}")
            
            # 调用原始中间件
            return original_func(request, call_next)
        
        # 替换中间件函数
        import tools.middlewares.logging_middleware
        tools.middlewares.logging_middleware.structured_logging_middleware = counting_middleware
        
        return counting_middleware
        
    except Exception as e:
        print(f"❌ 补丁失败: {e}")
        return None

def run_test():
    """运行测试"""
    print("=" * 60)
    print("🔧 调试重复日志问题")
    print("=" * 60)
    
    # 应用补丁
    print("1️⃣ 应用调试补丁...")
    patch_logging_middleware()
    
    # 直接运行您的测试用例
    print("\n2️⃣ 运行测试用例...")
    print("观察下面的输出，每个 🔍 表示中间件被调用一次")
    print("-" * 40)
    
    try:
        # 模拟您的测试用例
        import pytest
        from testcases.test_mock import test_get_users
        
        # 运行测试
        test_get_users()
        
        print("-" * 40)
        print("✅ 测试完成")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    run_test()